package com.blackfish.desktop;

import com.blackfish.bag.BagService;
import com.blackfish.common.model.BagBelong;
import com.blackfish.common.model.User;
import com.blackfish.common.untils.ShaUntil;
import com.blackfish.device.DeviceService;
import com.blackfish.user.UserService;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import com.blackfish.api.ApiService;
import com.blackfish.common.model.Module;
import com.jfinal.plugin.activerecord.Record;

import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;

public class DesktopController extends Controller {
    static DesktopService service = new DesktopService();
    static ApiService apiService = new ApiService();
    static UserService userService = new UserService();
    static DeviceService deviceService = new DeviceService();
    static BagService bagService = new BagService();
    static ShaUntil shaUntil = new ShaUntil();


    @Before(DesktopInterceptor.class)
    public void index() {
        //1.未登录的时候将user_id 为0的bag返回并显示
        //TODO 2.如果已经登陆那么将用户特殊的bag返回给前端加载
        //3.点击登陆图标时要向后台发卡请求,看是否已经登陆,如果已经登陆那么显示登陆成功,
        //TODO 4,登陆成功后主界面重新加载
        User user = null;
        try {
            user = (User) getSession().getAttribute("User");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (user == null) {
            List<Record> bagList = service.deskUserBagList("0");
            setAttr("bagPage", bagList);
            render("index.html");
        } else {
            List<Record> bagList = service.deskUserBagList(user.getId().toString());
            setAttr("bagPage", bagList);
            render("index.html");
        }
    }


    public void view() {
        int bagId = getParaToInt(0);
        List<Module> modules = service.deskModuleList(String.valueOf(bagId));
        String bagName = service.getBagName(bagId);

        User user = (User) getSession().getAttribute("User");
        if (user == null) {
            return;
        }

        BagBelong bagBelong = bagService.getBagBelong(bagId, user.getId());
        if (bagBelong == null) {
            return;
        }

        int bagInits = bagBelong.getVersion();

        String bagPath = bagBelong.getStaticdir();
        if (bagInits == 0) {
            redirect("/factory/initApp?bagBelong=" + bagBelong.getId());
        } else if (bagInits == 1) {
            String path = "F:\\Object\\Java\\jfBlackFish-web\\WebRoot\\factory\\product\\" + bagPath + "\\loads";
            File file = new File(path);
            // TODO 改为生成json到静态页面文件夹下
            if (!file.exists()) {
                boolean mkdir = file.mkdirs();
                if (mkdir) {
                    for (Module mod : modules) {
                        File modJson = new File(path + "/" + mod.getTitle() + ".json");
                        try {
                            modJson.createNewFile();
                            modJson.canWrite();
                        } catch (IOException e) {
                            // TODO 自动生成的 catch 块
                            e.printStackTrace();
                        }
                    }
                } else {
                    path = "null";
                }
            }
//            setAttr("moduleView", modules);
//            setAttr("requestPath", "../loads/" + bagName + "/");
            // setAttr("bagPath",bagPath);
            //render("bag.html");
            bagBelong.set("version", 2).update();
            setAttr("localpath","/factory/product/"+bagPath+"/html");
            render("/factory/product/"+bagPath + "/html/index.html");
        } else {
            setAttr("localpath","/factory/product/"+bagPath+"/html");
            //setSessionAttr("User",user);
            render("/factory/product/"+bagPath + "/html/index.html");
        }
    }

    public void ioEvent() throws Exception {
        User user = (User) getSession().getAttribute("User");
        if(user==null){
            renderText("error");
            return ;
        }

        String bagName = getPara("bagName");
        String moduleName = getPara("moduleName");

        int moduleId = service.getModuleId(moduleName, bagName,user.getId());
        List<String> deviceKeys = service.getDeviceId(moduleId);

        String active = service.replyActive(getPara("active"));
        String bagPath = shaUntil.getPathName(bagName,user.getName());
        apiService.addEventList(moduleId, active, "0", deviceKeys,bagPath);
        renderText("ok");
    }

    public void sldEvent() throws Exception {
        User user = (User) getSession().getAttribute("User");
        if(user==null){
            renderText("error");
            return ;
        }
        String bagName = getPara("bagName");
        String moduleName = getPara("moduleName");
        int moduleId = service.getModuleId(moduleName, bagName);
        List<String> deviceKeys = service.getDeviceId(moduleId);

        String active = service.replyActive(getPara("active"));
        String data = getPara("data"); //拖动的数值
        String bagPath = shaUntil.getPathName(bagName,user.getName());
        apiService.addEventList(moduleId, active, data, deviceKeys,bagPath);
        renderText("ok");
    }

    public void btnEvent() throws Exception {
        User user = (User) getSession().getAttribute("User");
        if(user==null){
            renderText("error");
            return ;
        }
        String bagName = getPara("bagName");
        String moduleName = getPara("moduleName");
        int moduleId = service.getModuleId(moduleName, bagName);
        List<String> deviceKeys = service.getDeviceId(moduleId);

        String active = service.replyActive(getPara("active"));
        String data = getPara("data");  //只是一般的点击
        String bagPath = shaUntil.getPathName(bagName,user.getName());
        apiService.addEventList(moduleId, active, "0", deviceKeys,bagPath);
        renderText("ok");
    }

    public void timEvent() throws Exception {
        User user = (User) getSession().getAttribute("User");
        if(user==null){
            renderText("error");
            return ;
        }
        String bagName = getPara("bagName");
        String moduleName = getPara("moduleName");
        int moduleId = service.getModuleId(moduleName, bagName);
        List<String> deviceKeys = service.getDeviceId(moduleId);

        String active = service.replyActive(getPara("active"));
        String data = getPara("data");
        String bagPath = shaUntil.getPathName(bagName,user.getName());
        apiService.addEventList(moduleId, active, data, deviceKeys,bagPath);
        renderText("ok");
    }

    public void chtEvent() throws Exception {
        User user = (User) getSession().getAttribute("User");
        if(user==null){
            renderText("error");
            return ;
        }
        String bagName = getPara("bagName");
        String moduleName = getPara("moduleName");
        int moduleId = service.getModuleId(moduleName, bagName);
        List<String> deviceKeys = service.getDeviceId(moduleId);

        String active = service.replyActive(getPara("active"));
        String data = getPara("data");
        String bagPath = shaUntil.getPathName(bagName,user.getName());
        apiService.addEventList(moduleId, active, data, deviceKeys,bagPath);
        renderText("ok");
    }

    public void plyEvent() throws Exception {
        User user = (User) getSession().getAttribute("User");
        if(user==null){
            renderText("error");
            return ;
        }
        String bagName = getPara("bagName");
        String moduleName = getPara("moduleName");
        int moduleId = service.getModuleId(moduleName, bagName);
        List<String> deviceKeys = service.getDeviceId(moduleId);

        String active = service.replyActive(getPara("active"));
        String data = getPara("data");//播放地址
        String bagPath = shaUntil.getPathName(bagName,user.getName());
        apiService.addEventList(moduleId, active, data, deviceKeys,bagPath);
        renderText("ok");
    }

    public void tlkEvent() throws Exception {
        User user = (User) getSession().getAttribute("User");
        if(user==null){
            renderText("error");
            return ;
        }
        String bagName = getPara("bagName");
        String moduleName = getPara("moduleName");
        int moduleId = service.getModuleId(moduleName, bagName);
        List<String> deviceKeys = service.getDeviceId(moduleId);

        String active = service.replyActive(getPara("active"));
        String data = getPara("data");//对话内容
        String bagPath = shaUntil.getPathName(bagName,user.getName());
        apiService.addEventList(moduleId, active, data, deviceKeys,bagPath);
        renderText("ok");
    }

    public void tlkClean() {
        String path = "./WebRoot" + getPara("path").substring(2);
        String write = " {\"time\":\"null\",\"content\":\"null\"}";
        File file = new File(path);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write(write);
            fileWriter.flush();
            fileWriter.close();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        renderText("ok");
    }

    public void plyPath() {
        int id = getParaToInt("id");
        String path = service.getPathById(id);
        renderText("{\"path\":\"" + path + "\"}");
    }


    public void login() {
        String haveLogin = (String) getSession().getAttribute("UserLoginAction");
        if (getRequest().getMethod().equals("GET")) {
            if (haveLogin == null) {
                render("login.html");
            } else if (haveLogin.equals("Yes")) {
                redirect("/desktop");
            } else {
                render("login.html");
            }
        } else {
            if (haveLogin == null) {
                String name = getPara("name");
                String password = getPara("pwd");
                User loginUser = userService.getByName(name, password);
                if (loginUser != null) {
                    setSessionAttr("UserLoginAction", "Yes");
                    setSessionAttr("User", loginUser);
                    redirect("/desktop");
                } else {
                    setSessionAttr("UserLoginAction", "No");
                }
            } else if (haveLogin.equals("Yes")) {
                redirect("/desktop");
            }
        }
    }

}
